package com.lfy.moss.components;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;

public class DesktopIcon extends JComponent {

    // 属性
    private Icon icon;
    private String text;
    private boolean isSelected = false;
    private boolean isHovered = false;
    private boolean isPressed = false;
    private boolean isDoubleClicked = false;

    // 颜色定义
    private static final Color SELECTION_COLOR = new Color(0, 120, 215, 80);
    private static final Color HOVER_COLOR = new Color(255, 255, 255, 30);
    private static final Color TEXT_COLOR = Color.WHITE;
    private static final Color TEXT_SHADOW_COLOR = new Color(0, 0, 0, 150);
    private static final Color SELECTION_BORDER_COLOR = new Color(0, 120, 215);

    // 尺寸设置
    private int iconSize = 48;
    private int padding = 8;
    private int textPadding = 4;
    private int cornerRadius = 4;

    // 事件监听器
    private ActionListener actionListener;
    private ActionListener doubleClickListener;

    // 动画效果
    private Timer hoverTimer;
    private float hoverAlpha = 0.0f;

    public DesktopIcon(Icon icon, String text) {
        this.icon = icon;
        this.text = text;
        initComponent();
    }

    public DesktopIcon(String imagePath, String text) {
        this.icon = loadImageIcon(imagePath);
        this.text = text;
        initComponent();
    }

    private void initComponent() {
        setOpaque(false);
        setFocusable(true);

        // 计算组件大小
        Font font = getSupportedChineseFont();
        FontMetrics fm = getFontMetrics(font);
        int textWidth = fm.stringWidth(text);
        int textHeight = fm.getHeight();

        int width = Math.max(iconSize, textWidth) + padding * 2;
        int height = iconSize + textHeight + textPadding + padding * 2;

        setPreferredSize(new Dimension(width, height));
        setSize(new Dimension(width, height));

        // 设置字体
        setFont(getSupportedChineseFont());

        // 添加鼠标监听器
        addMouseListener(new MouseAdapter() {
            private long lastClickTime = 0;

            @Override
            public void mouseEntered(MouseEvent e) {
                isHovered = true;
                setCursor(new Cursor(Cursor.HAND_CURSOR));
                startHoverAnimation(true);
            }

            @Override
            public void mouseExited(MouseEvent e) {
                isHovered = false;
                setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                startHoverAnimation(false);
            }

            @Override
            public void mousePressed(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1) {
                    isPressed = true;
                    requestFocusInWindow();
                    repaint();
                }
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                if (isPressed && e.getButton() == MouseEvent.BUTTON1) {
                    isPressed = false;

                    // 检测双击
                    long currentTime = System.currentTimeMillis();
                    if (currentTime - lastClickTime < 500) {
                        // 双击事件
                        isDoubleClicked = true;
                        if (doubleClickListener != null) {
                            doubleClickListener.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "doubleClick"));
                        }
                    } else {
                        // 单击事件
                        setSelected(true);
                        if (actionListener != null) {
                            actionListener.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "click"));
                        }
                    }
                    lastClickTime = currentTime;
                    repaint();
                }
            }

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2 && doubleClickListener != null) {
                    doubleClickListener.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "doubleClick"));
                }
            }
        });

        // 键盘监听器
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER || e.getKeyCode() == KeyEvent.VK_SPACE) {
                    if (doubleClickListener != null) {
                        doubleClickListener.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "enter"));
                    }
                }
            }
        });

        // 焦点监听器
        addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                repaint();
            }

            @Override
            public void focusLost(FocusEvent e) {
                setSelected(false);
                repaint();
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);

        int width = getWidth();
        int height = getHeight();

        // 绘制选中/悬停背景
        if (isSelected || isHovered || hasFocus()) {
            Color bgColor;
            if (isSelected || hasFocus()) {
                bgColor = new Color(SELECTION_COLOR.getRed(), SELECTION_COLOR.getGreen(),
                        SELECTION_COLOR.getBlue(), (int)(SELECTION_COLOR.getAlpha() * (0.5f + hoverAlpha * 0.5f)));
            } else {
                bgColor = new Color(HOVER_COLOR.getRed(), HOVER_COLOR.getGreen(),
                        HOVER_COLOR.getBlue(), (int)(HOVER_COLOR.getAlpha() * hoverAlpha));
            }

            g2d.setColor(bgColor);
            g2d.fill(new RoundRectangle2D.Float(0, 0, width, height, cornerRadius, cornerRadius));

            // 绘制选中边框
            if (isSelected || hasFocus()) {
                g2d.setColor(SELECTION_BORDER_COLOR);
                g2d.setStroke(new BasicStroke(1.5f));
                g2d.draw(new RoundRectangle2D.Float(1, 1, width - 2, height - 2, cornerRadius, cornerRadius));
            }
        }

        // 绘制按下效果
        if (isPressed) {
            g2d.setColor(new Color(0, 0, 0, 30));
            g2d.fill(new RoundRectangle2D.Float(0, 0, width, height, cornerRadius, cornerRadius));
        }

        // 计算图标位置
        int iconX = (width - iconSize) / 2;
        int iconY = padding;

        // 绘制图标
        if (icon != null) {
            // 如果按下，添加偏移效果
            int offsetX = isPressed ? 1 : 0;
            int offsetY = isPressed ? 1 : 0;

            // 缩放图标到指定大小
            Icon scaledIcon = scaleIcon(icon, iconSize, iconSize);
            scaledIcon.paintIcon(this, g2d, iconX + offsetX, iconY + offsetY);
        }

        // 绘制文本
        if (text != null && !text.isEmpty()) {
            FontMetrics fm = g2d.getFontMetrics();
            int textWidth = fm.stringWidth(text);
            int textHeight = fm.getHeight();

            int textX = (width - textWidth) / 2;
            int textY = iconY + iconSize + textPadding + fm.getAscent();

            // 如果按下，添加偏移效果
            int offsetX = isPressed ? 1 : 0;
            int offsetY = isPressed ? 1 : 0;

            // 绘制文本阴影
            g2d.setColor(TEXT_SHADOW_COLOR);
            g2d.drawString(text, textX + 1 + offsetX, textY + 1 + offsetY);

            // 绘制文本
            g2d.setColor(TEXT_COLOR);
            g2d.drawString(text, textX + offsetX, textY + offsetY);
        }

        g2d.dispose();
    }

    private Icon scaleIcon(Icon icon, int width, int height) {
        if (icon.getIconWidth() == width && icon.getIconHeight() == height) {
            return icon;
        }

        BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = scaledImage.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 绘制原始图标到缓冲图像
        if (icon instanceof ImageIcon) {
            Image img = ((ImageIcon) icon).getImage();
            g2d.drawImage(img, 0, 0, width, height, null);
        } else {
            icon.paintIcon(null, g2d, 0, 0);
        }

        g2d.dispose();
        return new ImageIcon(scaledImage);
    }

    private Icon loadImageIcon(String imagePath) {
        try {
            ImageIcon originalIcon = new ImageIcon(imagePath);
            if (originalIcon.getIconWidth() <= 0) {
                // 如果图片加载失败，返回默认图标
                return createDefaultIcon();
            }
            return originalIcon;
        } catch (Exception e) {
            return createDefaultIcon();
        }
    }

    public Icon createDefaultIcon() {
        return new Icon() {
            @Override
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 绘制默认文件图标
                g2d.setColor(new Color(70, 130, 180));
                g2d.fillRoundRect(x + 4, y + 2, getIconWidth() - 8, getIconHeight() - 4, 4, 4);

                g2d.setColor(new Color(100, 160, 210));
                g2d.fillRoundRect(x + 6, y + 4, getIconWidth() - 12, 8, 2, 2);
                g2d.fillRoundRect(x + 6, y + 14, getIconWidth() - 12, 6, 2, 2);
                g2d.fillRoundRect(x + 6, y + 22, getIconWidth() - 12, 6, 2, 2);

                g2d.dispose();
            }

            @Override
            public int getIconWidth() {
                return iconSize;
            }

            @Override
            public int getIconHeight() {
                return iconSize;
            }
        };
    }

    private Font getSupportedChineseFont() {
        String[] fontNames = {
                "Microsoft YaHei",
                "SimHei",
                "SimSun",
                "Dialog",
                "SansSerif"
        };

        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] availableFonts = ge.getAvailableFontFamilyNames();

        for (String fontName : fontNames) {
            for (String availableFont : availableFonts) {
                if (availableFont.equals(fontName)) {
                    return new Font(fontName, Font.PLAIN, 11);
                }
            }
        }

        return new Font(Font.SANS_SERIF, Font.PLAIN, 11);
    }

    private void startHoverAnimation(boolean fadeIn) {
        if (hoverTimer != null && hoverTimer.isRunning()) {
            hoverTimer.stop();
        }

        hoverTimer = new Timer(20, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (fadeIn) {
                    hoverAlpha += 0.1f;
                    if (hoverAlpha >= 1.0f) {
                        hoverAlpha = 1.0f;
                        hoverTimer.stop();
                    }
                } else {
                    hoverAlpha -= 0.1f;
                    if (hoverAlpha <= 0.0f) {
                        hoverAlpha = 0.0f;
                        hoverTimer.stop();
                    }
                }
                repaint();
            }
        });
        hoverTimer.start();
    }

    // 公共方法
    public void setSelected(boolean selected) {
        if (this.isSelected != selected) {
            this.isSelected = selected;
            repaint();
        }
    }

    public boolean isSelected() {
        return isSelected;
    }

    public void setText(String text) {
        this.text = text;
        repaint();
    }

    public String getText() {
        return text;
    }

    public void setIcon(Icon icon) {
        this.icon = icon;
        repaint();
    }

    public Icon getIcon() {
        return icon;
    }

    public void setIconSize(int iconSize) {
        this.iconSize = iconSize;
        revalidate();
        repaint();
    }

    public int getIconSize() {
        return iconSize;
    }

    // 事件监听器方法
    public void addActionListener(ActionListener listener) {
        this.actionListener = AWTEventMulticaster.add(this.actionListener, listener);
    }

    public void removeActionListener(ActionListener listener) {
        this.actionListener = AWTEventMulticaster.remove(this.actionListener, listener);
    }

    public void addDoubleClickListener(ActionListener listener) {
        this.doubleClickListener = AWTEventMulticaster.add(this.doubleClickListener, listener);
    }

    public void removeDoubleClickListener(ActionListener listener) {
        this.doubleClickListener = AWTEventMulticaster.remove(this.doubleClickListener, listener);
    }

    // 创建各种图标的方法
    public static Icon createFolderIcon() {
        return new Icon() {
            @Override
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 文件夹图标
                g2d.setColor(new Color(255, 193, 7));
                g2d.fillRoundRect(x + 2, y + 12, 44, 30, 4, 4);
                g2d.fillRoundRect(x + 2, y + 8, 18, 8, 4, 4);

                g2d.setColor(new Color(255, 235, 59));
                g2d.fillRoundRect(x + 4, y + 14, 40, 26, 3, 3);

                g2d.dispose();
            }

            @Override
            public int getIconWidth() { return 48; }

            @Override
            public int getIconHeight() { return 48; }
        };
    }

    public static Icon createAppIcon() {
        return new Icon() {
            @Override
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 应用程序图标
                g2d.setColor(new Color(33, 150, 243));
                g2d.fillRoundRect(x + 4, y + 4, 40, 40, 8, 8);

                g2d.setColor(Color.WHITE);
                g2d.setFont(new Font("Dialog", Font.BOLD, 16));
                FontMetrics fm = g2d.getFontMetrics();
                String text = "App";
                int textX = x + (48 - fm.stringWidth(text)) / 2;
                int textY = y + (48 - fm.getHeight()) / 2 + fm.getAscent();
                g2d.drawString(text, textX, textY);

                g2d.dispose();
            }

            @Override
            public int getIconWidth() { return 48; }

            @Override
            public int getIconHeight() { return 48; }
        };
    }

    public static Icon createImageIcon() {
        return new Icon() {
            @Override
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 图片图标
                g2d.setColor(new Color(76, 175, 80));
                g2d.fillRoundRect(x + 4, y + 6, 40, 36, 4, 4);

                g2d.setColor(new Color(129, 199, 132));
                g2d.fillOval(x + 12, y + 12, 8, 8);

                g2d.setColor(new Color(165, 214, 167));
                int[] xPoints = {x + 8, x + 20, x + 32, x + 40};
                int[] yPoints = {y + 35, y + 25, y + 30, y + 38};
                g2d.fillPolygon(xPoints, yPoints, 4);

                g2d.dispose();
            }

            @Override
            public int getIconWidth() { return 48; }

            @Override
            public int getIconHeight() { return 48; }
        };
    }

    public static Icon createMusicIcon() {
        return new Icon() {
            @Override
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 音乐图标
                g2d.setColor(new Color(233, 30, 99));
                g2d.fillOval(x + 8, y + 28, 12, 12);
                g2d.fillOval(x + 28, y + 20, 12, 12);

                g2d.setStroke(new BasicStroke(3));
                g2d.drawLine(x + 20, y + 34, x + 28, y + 26);
                g2d.drawLine(x + 28, y + 8, x + 28, y + 26);
                g2d.drawLine(x + 28, y + 8, x + 35, y + 12);

                g2d.dispose();
            }

            @Override
            public int getIconWidth() { return 48; }

            @Override
            public int getIconHeight() { return 48; }
        };
    }

    public static Icon createVideoIcon() {
        return new Icon() {
            @Override
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 视频图标
                g2d.setColor(new Color(255, 87, 34));
                g2d.fillRoundRect(x + 4, y + 14, 32, 20, 4, 4);

                g2d.setColor(Color.WHITE);
                int[] xPoints = {x + 15, x + 15, x + 25};
                int[] yPoints = {y + 19, y + 29, y + 24};
                g2d.fillPolygon(xPoints, yPoints, 3);

                // 摄像头
                g2d.setColor(new Color(183, 28, 28));
                g2d.fillOval(x + 36, y + 18, 8, 12);

                g2d.dispose();
            }

            @Override
            public int getIconWidth() { return 48; }

            @Override
            public int getIconHeight() { return 48; }
        };
    }

    public static Icon createSettingsIcon() {
        return new Icon() {
            @Override
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 设置图标（齿轮）
                g2d.setColor(new Color(96, 125, 139));
                g2d.fillOval(x + 12, y + 12, 24, 24);

                g2d.setColor(new Color(69, 90, 100));
                for (int i = 0; i < 8; i++) {
                    double angle = i * Math.PI / 4;
                    int rx = (int) (Math.cos(angle) * 16);
                    int ry = (int) (Math.sin(angle) * 16);
                    g2d.fillRect(x + 24 + rx - 1, y + 24 + ry - 1, 3, 3);
                }

                g2d.setColor(Color.WHITE);
                g2d.fillOval(x + 20, y + 20, 8, 8);

                g2d.dispose();
            }

            @Override
            public int getIconWidth() { return 48; }

            @Override
            public int getIconHeight() { return 48; }
        };
    }

    public static Icon createNetworkIcon() {
        return new Icon() {
            @Override
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 网络图标
                g2d.setColor(new Color(3, 169, 244));
                g2d.setStroke(new BasicStroke(3));

                // 绘制地球
                g2d.drawOval(x + 8, y + 8, 32, 32);
                g2d.drawOval(x + 16, y + 8, 16, 32);
                g2d.drawLine(x + 8, y + 20, x + 40, y + 20);
                g2d.drawLine(x + 8, y + 28, x + 40, y + 28);

                g2d.dispose();
            }

            @Override
            public int getIconWidth() { return 48; }

            @Override
            public int getIconHeight() { return 48; }
        };
    }

    public static Icon createTrashIcon() {
        return new Icon() {
            @Override
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 回收站图标
                g2d.setColor(new Color(158, 158, 158));
                g2d.fillRect(x + 12, y + 16, 24, 26);
                g2d.fillRect(x + 8, y + 14, 32, 4);
                g2d.fillRect(x + 16, y + 8, 16, 6);

                // 垃圾线条
                g2d.setColor(new Color(97, 97, 97));
                g2d.setStroke(new BasicStroke(2));
                g2d.drawLine(x + 18, y + 20, x + 18, y + 36);
                g2d.drawLine(x + 24, y + 20, x + 24, y + 36);
                g2d.drawLine(x + 30, y + 20, x + 30, y + 36);

                g2d.dispose();
            }

            @Override
            public int getIconWidth() { return 48; }

            @Override
            public int getIconHeight() { return 48; }
        };
    }
}